package com.lsh.payment.core.service.mispurse.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.payment.api.model.mispurse.MisRefundResponse;
import com.lsh.payment.core.model.payenum.PayChannel;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.model.refund.PayRefund;
import com.lsh.payment.core.service.mispurse.IMisPurseRefundService;
import com.lsh.payment.core.strategy.config.MisPayConfig;
import com.lsh.payment.core.util.HttpClientUtils;
import com.lsh.payment.core.util.pay.wxpay.WxSignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * Created by peter on 19/3/14.
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
@Slf4j
public class MisPurseRefundServiceImpl implements IMisPurseRefundService {

    private static final String REFUND_API = "/trade/info/refund";

    private static final String REFUND_QUERY = "/trade/info/notify";


    /**
     * 退款请求
     *
     * @param payRefund
     * @param payDeal
     * @return
     */
    @Override
    public MisRefundResponse refund(PayRefund payRefund, PayDeal payDeal) {

        JSONObject ext = JSON.parseObject(payRefund.getExt());
        String uid = ext.getString("uid");
        String payMethod;
        if (null == payDeal) {
            payMethod = "2";
        } else {
            if (payDeal.getTradeType() == PayChannel.PURSE_ON_CREDIT_PAY.getCode()) {
                payMethod = "3";
            } else if (payDeal.getTradeType() == PayChannel.PURSE_PRE_PAY.getCode()) {
                payMethod = "4";
            } else if (payDeal.getTradeType() == PayChannel.PURSE_BALANCE_PAY.getCode()) {
                payMethod = "2";
            } else {
                payMethod = "0";
            }
        }

        Map<String, Object> misRefundRequestBody = new HashMap<>(12);

        misRefundRequestBody.put("appid", MisPayConfig.APPID);
        misRefundRequestBody.put("uid", uid);
        misRefundRequestBody.put("pay_method", payMethod);
        if (null != payDeal) {
            misRefundRequestBody.put("to_trade_id", payDeal.getChannelTransaction());
        }
        misRefundRequestBody.put("out_trade_no", payRefund.getPaymentRefundNo());
        misRefundRequestBody.put("money", payRefund.getRefundAmount().toString());

        int timestamp = (int) (System.currentTimeMillis() / 1000);

        String sign = WxSignature.getMisSign(misRefundRequestBody, MisPayConfig.APPID, timestamp);
        Map<String, String> headMap = new HashMap<>();

        headMap.put("timestamp", timestamp + "");
        headMap.put("accesskey", MisPayConfig.APPID);
        headMap.put("sign", sign);

        log.info("mis退款参数 {}", JSON.toJSONString(misRefundRequestBody));
        String misResultStr = HttpClientUtils.doPost(MisPayConfig.PAY_API + REFUND_API, misRefundRequestBody, headMap);
        log.info("mis退款结果 {}", misResultStr);
        JSONObject misResult = JSON.parseObject(misResultStr);
        MisRefundResponse misRefundResponse = new MisRefundResponse();
        if ("0".equals(misResult.getString("ret"))) {
            misRefundResponse.setRet(0);
            misRefundResponse.setMsg("success");
            JSONObject content = misResult.getJSONObject("content");
            misRefundResponse.setTransactionId(content.getString("trade_id"));
            misRefundResponse.setTrade_money(content.getString("trade_money"));
            misRefundResponse.setStatus(content.getString("status"));
        } else {
            misRefundResponse.setRet(misResult.getInteger("ret"));
            misRefundResponse.setMsg("fail");
        }

        return misRefundResponse;
    }

    /**
     * 查询退款信息
     *
     * @param payRefund
     * @param payDeal
     * @return
     */
    @Override
    public MisRefundResponse refundQuery(PayRefund payRefund, PayDeal payDeal) {

        Map<String, Object> misRefundRequestBody = new HashMap<>(12);

        misRefundRequestBody.put("appid", MisPayConfig.APPID);
        misRefundRequestBody.put("trade_id", payRefund.getChannelRefundId());

        int timestamp = (int) (System.currentTimeMillis() / 1000);

        String sign = WxSignature.getMisSign(misRefundRequestBody, MisPayConfig.APPID, timestamp);
        Map<String, String> headMap = new HashMap<>();

        headMap.put("timestamp", timestamp + "");
        headMap.put("accesskey", MisPayConfig.APPID);
        headMap.put("sign", sign);

        log.info("mis退款参数 {}", JSON.toJSONString(misRefundRequestBody));
        String misResultStr = HttpClientUtils.doPost(MisPayConfig.PAY_API + REFUND_QUERY, misRefundRequestBody, headMap);

        JSONObject misQueryResult = JSON.parseObject(misResultStr);
        //校验返回参数
        MisRefundResponse misPayResponse = new MisRefundResponse();
        if ("0".equals(misQueryResult.getString("ret")) && true == misQueryResult.getBoolean("content")) {

            misPayResponse.setRet(0);
            misPayResponse.setMsg("success");
        } else {
            misPayResponse.setRet(misQueryResult.getInteger("ret"));
            misPayResponse.setMsg("fail");
        }

        return misPayResponse;
    }
}
